package com.myspring.web.view.excel;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

public class ExcelMethodProcessor implements HandlerMethodReturnValueHandler {
	
	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		return (AnnotationUtils.findAnnotation(returnType.getContainingClass(), Excel.class) != null ||
				returnType.getMethodAnnotation(Excel.class) != null);
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest) throws Exception {
		mavContainer.setRequestHandled(true);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		ExcelView view = new ExcelView();
		
		if (returnValue instanceof Map) {
			view.render( (Map)returnValue, request, response);
		} else {
			ModelMap model = new ModelMap();
			model.addAttribute("returnValue", returnValue);
			view.render(model, request, response);
		}
	}

}
